package patrol.mobile.com.mobilepatrol.activity.road_survey;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.dl7.recycler.adapter.BaseQuickAdapter;
import com.dl7.recycler.listener.OnRecyclerViewItemClickListener;
import com.dl7.recycler.listener.OnRecyclerViewItemLongClickListener;
import com.google.gson.Gson;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

import butterknife.BindView;
import patrol.mobile.com.mobilepatrol.DBHelper;
import patrol.mobile.com.mobilepatrol.PatrolApp;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.adapter.TrafficInvestListAdapter;
import patrol.mobile.com.mobilepatrol.api.AppException;
import patrol.mobile.com.mobilepatrol.api.DataUtil;
import patrol.mobile.com.mobilepatrol.api.MyHandler;
import patrol.mobile.com.mobilepatrol.bean.RoadInvestUploadInfoBean;
import patrol.mobile.com.mobilepatrol.bean.RouteSurveyTaskStructBO;
import patrol.mobile.com.mobilepatrol.bean.TrafficInvestBaseInfo;
import patrol.mobile.com.mobilepatrol.bean.User;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.UIHelper;
import patrol.mobile.com.mobilepatrol.widget.dialog.AppleDialog;

/**
 * Created by 健 on 2014/8/25.
 */
public class TrafficInvestActivity extends BaseActivity {

    private Gson gson=new Gson();

//    private Button startInvest;
//    private Button modifyInvest;
//    private Button deleteInvest;
//    private Button uploadInvestInfo;
//    private Button uploadInvestAll;
    private User userinfo;
    private BaseQuickAdapter<TrafficInvestBaseInfo> mAdapter;
    private List<TrafficInvestBaseInfo> mList = new ArrayList<>();
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    private int selectItemIndex=-1;
    private ProgressDialog progressDialog;
    private DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



    }
    @Override
    protected int attachLayoutRes() {
        return R.layout.comment_list;
    }



    @Override
    public void initTitle() {
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(TrafficInvestActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("公路技术状况调查");
        iv_right_title.setVisibility(View.VISIBLE);
        iv_right_title.setImageResource(R.mipmap.add);
        iv_right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                UIHelper.startTrafficInvestBaseInfoActivity(TrafficInvestActivity.this, null);
                CommonUtil.openNewActivityAnim(TrafficInvestActivity.this, false);
            }
        });

    }

    @Override
    public void initData() {
        super.initData();
        dbHelper=new DBHelper(this);
        userinfo= UserManager.getUser();
        updateTableData();
    }

    public void setListener() {
        mAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                UIHelper.startTrafficInvestBaseInfoActivity(TrafficInvestActivity.this, mList.get(position));
            }
        });
        mAdapter.setOnItemLongClickListener(new OnRecyclerViewItemLongClickListener() {
            @Override
            public boolean onItemLongClick(View view, final int position) {
                final AppleDialog dialog = new AppleDialog(TrafficInvestActivity.this,R.style.Dialog,"确认删除？");
                dialog.show();
                dialog.setmListener(new AppleDialog.SureListener() {
                    @Override
                    public void onSure() {
                        dbHelper.deleteInvestBaseInfo(mList.get(position));
                        updateTableData();

                    }
                });
                return false;
            }
        });
        //查
        //删
//        startInvest.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                UIHelper.startTrafficInvestBaseInfoActivity(TrafficInvestActivity.this, null);
//            }
//        });
//        modifyInvest.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (selectItemIndex == -1)
//                    showToast("请先选择一条公路状况调查信息");
//                else
//                    UIHelper.startTrafficInvestBaseInfoActivity(TrafficInvestActivity.this, dataInfo.get(selectItemIndex));
//            }
//        });
//        deleteInvest.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (selectItemIndex == -1)
//                    showToast("请先选择一条公路状况调查信息");
//                else{
//                    AlertDialog.Builder builder=new AlertDialog.Builder(TrafficInvestActivity.this);
//                    builder.setTitle("提示");
//                    builder.setMessage("删除选中信息？");
//                    builder.setPositiveButton("确认",new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialogInterface, int i) {
//                            dbHelper.deleteInvestBaseInfo(dataInfo.get(selectItemIndex));
//                            showToast("删除成功");
//                            dataInfo.remove(selectItemIndex);
//                        }
//                    });
//                    builder.setNegativeButton("取消",null);
//                    builder.create().show();
//                }
//
//            }
//        });
//        uploadInvestInfo.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if(selectItemIndex==-1)
//                    UIHelper.ToastMessageCenter(TrafficInvestActivity.this,"请先选择一条公路状况调查信息");
//                else{
//                    TrafficInvestBaseInfo baseInfo=dataInfo.get(selectItemIndex);
//                    /*if(baseInfo.getStatus()==1){
//                        UIHelper.ToastMessageCenter(TrafficInvestActivity.this,"error:该信息已经上传，不能重复上传！");
//                    }else {*/
//                        List<TrafficInvestBaseInfo> listInfo = new ArrayList<TrafficInvestBaseInfo>();
//                        listInfo.add(baseInfo);
//                        uploadInvestInfo(listInfo);
//                 //   }
//                }
//
//            }
//        });
//
//        webView.setWebViewClient(new WebViewClient(){
//            @Override
//            public void onPageFinished(WebView view, String url) {
//                updateTableData();
//            }
//        });

//        uploadInvestAll.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                List<TrafficInvestBaseInfo> listInfo=new ArrayList<TrafficInvestBaseInfo>();
//                for(TrafficInvestBaseInfo baseInfo:dataInfo){
//                    if(baseInfo.getStatus()==0)
//                        listInfo.add(baseInfo);
//                }
//                if(listInfo.size()>0)
//                    uploadInvestInfo(listInfo);
//            }
//        });
    }


    public void initView() {
        super.initView();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new TrafficInvestListAdapter(TrafficInvestActivity.this, mList);
        recyclerView.setAdapter(mAdapter);
    }



    private void updateTableData(){
    	if(userinfo.orgtype.equals("分局")){
            mList= dbHelper.getInvestBaseInfoAll(userinfo.bmname);
    	}else{
            mList=dbHelper.getInvestBaseInfoAll();
    	}
        mAdapter.updateItems(mList);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    @Override
    protected void onResume() {
        selectItemIndex=-1;
        if(mList!=null){
            updateTableData();
        }
        super.onResume();
    }

    private Handler uploadSuccess=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            showToast("上传成功！");
            updateTableData();
            if(progressDialog.isShowing())
                progressDialog.dismiss();
        }
    };
    private final Queue<TrafficInvestBaseInfo> uploadQueue=new ArrayDeque<TrafficInvestBaseInfo>();

    public void goDetail(TrafficInvestBaseInfo info){
        UIHelper.startInvestDetailCatalogActivity(this,info);
    }
    public void uploadInvestInfo(TrafficInvestBaseInfo uploadInfo) {
        if(progressDialog==null) {
            progressDialog = ProgressDialog.show(TrafficInvestActivity.this, "提示", "数据上传中,请稍候...");
            progressDialog.setCancelable(true);
        }else
            progressDialog.show();

        synchronized (uploadQueue) {
            uploadQueue.add(uploadInfo);
            uploadQueue.notifyAll();
        }

        if(uploadDetaiImgThread.getState()== Thread.State.NEW)
            uploadDetaiImgThread.start();
    }
    private Thread uploadDetaiImgThread=new Thread(){
        @Override
        public void run() {
            while(true){
                try {
                    if(Thread.interrupted())
                        break;

                    if (uploadQueue.size() == 0)
                        synchronized (uploadQueue) {
                            uploadSuccess.sendEmptyMessage(0);
                            uploadQueue.wait();
                        }
                    if (uploadQueue.size() > 0) {
                        TrafficInvestBaseInfo baseInfo;
                        synchronized (uploadQueue) {
                            baseInfo = uploadQueue.peek();
                        }
                        RoadInvestUploadInfoBean uploadInfo=new RoadInvestUploadInfoBean();
                        uploadInfo.setBaseInfo(baseInfo);
                        String state=baseInfo.getSurveyType().equals("复核")?"复核":"";
                        uploadInfo.setTaskStrcut(dbHelper.getRouteSurveyTaskStructInfo(baseInfo.getDetailID(),
                                state,baseInfo));

                        List<String> structIds=new ArrayList<String>();
                        for(RouteSurveyTaskStructBO struct:uploadInfo.getTaskStrcut()){
                            structIds.add(struct.getiD());
                        }
                        uploadInfo.setTaskStructData(dbHelper.getRouteTaskDataInfo(structIds));

                        DataUtil.uploadInvestInfo((PatrolApp) getApplication(), uploadResultHandler, gson.toJson(uploadInfo));

                        synchronized (uploadQueue) {
                            uploadQueue.wait();
                        }
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    private Handler uploadResultHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            TrafficInvestBaseInfo info = uploadQueue.poll();
            if(msg.what== MyHandler.MSG_SUCCESS){
                info.setStatus(1);
                dbHelper.updateInvestBaseInfo(info);
                updateTableData();

            }else if(msg.what==MyHandler.MSG_FAILURE){
                if(msg.obj!=null)
                    UIHelper.ToastMessageCenter(TrafficInvestActivity.this,msg.obj.toString());
            }else if(msg.what==MyHandler.MSG_ERR){
                AppException ae= (AppException) msg.obj;
                ae.makeToast(TrafficInvestActivity.this);
            }
            synchronized (uploadQueue) {
                uploadQueue.notifyAll();
            }
        }
    };
}
